package org.fujene.memoryblock.structure;

import java.util.ArrayList;

import org.fujene.constants.Constants;

import static org.fujene.memoryblock.structure.MemoryTypes.*;

public class MemoryTypeSet{
	private ArrayList<MemType> blocks;

	public MemoryTypeSet(){
		blocks = new ArrayList<MemType>();
	}

	public void register(String name, MemoryTypes addClass, int repetition, int length){
		MemType blk = new MemType(name, repetition, addClass);
		blocks.add(blk);
		if(addClass == INTEGER) blk.setClass(new FixedLengthInteger(length));
		else if(addClass == LONG) blk.setClass(new FixedLengthLong(length));
		else if(addClass == POINTER) blk.setClass(new FixedLengthPointer(length - Constants.BYTE_LOCALPTR));
		else if(addClass == STRING) blk.setClass(new VariableLengthString(0));
	}

	public int totalSize(){
		int total = 0;

		for(int i = 0; i < blocks.size(); i++)
			total += blocks.get(i).totalSize();

		return total;
	}

	public int getIndex(String name){
		for(int i = 0; i < blocks.size(); i++){
			if(blocks.get(i).getName().equals(name)) return i;
		}
		return -1;
	}

	public SerializableNumber<?> getvalues(int outerIndex, int innerIndex){
		if(outerIndex >= blocks.size()) return null;
		return blocks.get(outerIndex).getClassType(innerIndex);
	}

	public byte[] getByteArray(int index){
		if(index >= blocks.size()) return null;
		return blocks.get(index).getBytes(index);
	}

	public int advance(int index){
		int subtotal = 0;

		for(int i = 0; i < index; i++)
			subtotal += blocks.get(i).totalSize();

		return subtotal;
	}

	public byte[] getConcatByteArray(){
		byte[] output = new byte[totalSize()];
		byte[] subbyte;
		int total = 0;

		for(int i = 0; i < blocks.size(); i++){
			subbyte = blocks.get(i).getConcatBytes();
			System.arraycopy(subbyte, 0, output, total, subbyte.length);
			total += subbyte.length;
		}

		return output;
	}
	
	public int readlength(int index) {
		return blocks.get(index).size();
	}
}
